package com.jackstraw.jack_base.datasource.database.generator.entity;

import com.jackstraw.jack_base.util.StringUtil;
import lombok.Data;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 表数据
 */
@Data
public class TableEntity {
    /**
     * 表的名称
     */
    private String tableName;
    /**
     * 表的备注
     */
    private String comments;

    /**
     * 数据库引擎
     */
    private String engine;

    private Date createTime;

    /**
     * 表的主键
     */
    private List<ColumnEntity> pkS = new ArrayList<>();

    /**
     * 表的列名(不包含主键)
     */
    private List<ColumnEntity> columns = new ArrayList<>();

    /**
     * 所有的字段
     */
    private List<ColumnEntity> allColumns = new ArrayList<>();

    /**
     * 类名(第一个字母大写)，如：sys_user => SysUser
     */
    private String className;

    /**
     * 类名(第一个字母小写)，如：sys_user => sysUser
     */
    private String classname;


    /**
     * 是否含有BigDecimal类型
     */
    private Boolean hasBigDecimal = Boolean.FALSE;
    /**
     * 是否含有时间类型
     */
    private Boolean hasDate = Boolean.FALSE;
    /**
     * 主键是否含有BigDecimal类型
     */
    private Boolean hasKeyBigDecimal = Boolean.FALSE;
    /**
     * 主键是否含有时间类型
     */
    private Boolean hasKeyDate = Boolean.FALSE;


    public String getClassName() {
        return className;
    }

    public String getClassname() {
        return classname;
    }

    public void setClassName(String className) {
        this.className = className;
    }

    public void setClassname(String classname) {
        this.classname = classname;
    }


    /**
     * 拼接主键条件
     *
     * @return
     */
    public String primaryKeyConditions() {
        //"ID= #{id}"
        String condition = "%s = #{%s}";


        StringBuilder stringBuilder = new StringBuilder();

        for (int i = 0; i < pkS.size(); i++) {
            ColumnEntity columnEntity = pkS.get(i);
            stringBuilder.append(
                    StringUtil.format(condition, columnEntity.getColumnName(), columnEntity.getFieldName()));
            if (i != pkS.size() - 1) {
                stringBuilder.append("\n\t\t\t and ");
            }
        }

        return stringBuilder.toString();
    }

    /**
     * 拼接主键条件
     *
     * @return
     */
    public String primaryKeyRecordConditions() {
        //"ID= #{id}"
        String condition = "%s = record.#{%s}";

        StringBuilder stringBuilder = new StringBuilder();

        for (int i = 0; i < pkS.size(); i++) {
            ColumnEntity columnEntity = pkS.get(i);
            stringBuilder.append(
                    StringUtil.format(condition, columnEntity.getColumnName(), columnEntity.getFieldName()));
            if (i != pkS.size() - 1) {
                stringBuilder.append(" and ");
            }
        }

        return stringBuilder.toString();
    }
}
